package com.tianqu.tms.core.Camera;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.util.DateUtil;
import com.tianqu.tms.core.util.ImageUtils;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
/**
 * 摄像头调用类
 * 
 * @author Administrator
 *
 */
public class CameraPhotoUpload extends HttpServlet {
	private Logger LOGGER = Logger.getLogger(CameraPhotoUpload.class);
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	public void processRequest(HttpServletRequest request,
			HttpServletResponse response)

	throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
        //获得摄像头按钮参数
		String buttonType=request.getParameter("buttonType");
		String bitmap_data = request.getParameter("bitmap_data");
		int width = Integer.parseInt(request.getParameter("width"));
		int height = Integer.parseInt(request.getParameter("height"));
		BufferedImage img = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		try {
			int w = width;
			int h = height;
			int[] pixels = new int[w * h];
			String[] m_tempPics = bitmap_data.split(",");
			for (int x = 0; x < w; x++) {
				for (int y = 0; y < h; y++) {
					long pic_argb = (long) Long
							.parseLong(m_tempPics[x * h + y]);
					int a = (int) (pic_argb >> 24 & 0xFF);
					int r = (int) (pic_argb >> 16 & 0xFF);
					int g = (int) (pic_argb >> 8 & 0xFF);
					int b = (int) (pic_argb & 0xFF);
					pixels[y * w + x] = new Color(r, g, b, a).getRGB();
				}
			}
			img.setRGB(0, 0, w, h, pixels, 0, w);
			img.flush();
			ByteArrayOutputStream bao = new ByteArrayOutputStream();
			//ImageIO.write(img, "jpg", bao);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bao);
			encoder.encode(img);
			
			//
			byte[] data = bao.toByteArray();
			String path =ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.UPLOADTMP_CONTEXT_ROOT_KEY));
			// 生成随机文件名
			String saveName = UUID.randomUUID().toString();
			;
			String fileName = saveName + ".jpg";
			// 写图片
			File f = new File(path + fileName);
			DataOutputStream dos = new DataOutputStream(new FileOutputStream(f));
			dos.write(data);
			dos.flush();
			dos.close();
			response.setContentType("text/xml");
			response.getWriter().write(buttonType+"," + fileName);
		} catch (Exception ex) {
			LOGGER.error("CameraPhotoUpload error" + ex);
			response.setContentType("text/xml");
			response.getWriter().write("保存失败");
		}
	}
	
	public void mkDir(File file){
	  if(file.getParentFile().exists()){
	   file.mkdir();
	  }else{
	   mkDir(file.getParentFile());
	   file.mkdir();
	  }
    }
	
	protected String getImagePath(HttpServletRequest request,String modulePath){
		String path = request.getSession().getServletContext().getRealPath("/").replace("/tmsweb", "")+DateUtil.getCurrentYear()+modulePath;
		File file  = new File(path);
	    if (!file.exists()) file.mkdirs();
		return path;
	}
}
